//
//  CarnivalsTableDataViewController.m
//  PartyAnimal
//
//  Created by Hilary Muludiang on 3/12/12.
//  Copyright 2012 Versatile Systems, Inc. All rights reserved.
//

#import "CarnivalsTableDataViewController.h"
#import "StackMob.h"
#import "CarnivalsCategoriesTableDataViewController.h"
#import	"PartyAnimalAppDelegate.h"
#import "PartyAnimalNavigatorViewController.h"
#import "AddACarnivalViewController.h"
#import "iBacchanal.h"

@implementation CarnivalsTableDataViewController
@synthesize carnivalsTableDataView;
@synthesize carnivalsTableData;
@synthesize passedValue;
@synthesize carnivalsCategoriesTableDataViewController;
@synthesize contentView;



-(void)reachabilityChanged:(NSNotification *)note{
	
	Reachability* curReach = [note object];
	NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
	
	NetworkStatus netStatus = [curReach currentReachabilityStatus];
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	switch (netStatus){
		case NotReachable:{
			//show an alert to let the user know that they can't connect...
			UIAlertView *alert = [[[UIAlertView alloc] initWithTitle: nil message: bacchanal.downMessage
															delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil] autorelease];
			[alert show];
			bacchanal.networkUp = NO;
			self.navigationItem.rightBarButtonItem.enabled = NO;
			self.navigationItem.leftBarButtonItem.enabled = NO;
			break;
		}
		default:{
			// Network is reachable
			UIAlertView *alert = [[[UIAlertView alloc] initWithTitle: nil message: bacchanal.upMessage
															delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil] autorelease];
			[alert show];
			[self buildTable];
			bacchanal.networkUp = YES;
			self.navigationItem.rightBarButtonItem.enabled = YES;
			self.navigationItem.leftBarButtonItem.enabled = YES;
			break;
		}
			
    }
}

-(void)getYearsData{
	
	iBacchanal *bacchanal = [iBacchanal sharedUser];			 
	
	carnivalsTableData = [[NSMutableArray alloc] init];
	NSMutableArray *temp = [[NSMutableArray alloc] init];
	for (NSDictionary *carnival in bacchanal.carnivalsData)
	{
		NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
		[dateFormat setDateFormat:@"yyyy-MM-dd"];
		NSDate *tempdate = [dateFormat dateFromString:[carnival objectForKey:@"startDate"]];
		[dateFormat setDateFormat:@"yyyy"];
		NSString *tempStrDate = [dateFormat stringFromDate:tempdate];
		[temp addObject:tempStrDate];
		[dateFormat release];
	}	
	carnivalsTableData = [[[NSSet setWithArray:temp] allObjects] retain];
	[temp release];
	
}

-(void)getCitiesData{
	
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	carnivalsTableData = [[NSMutableArray alloc] init];
	NSMutableArray *temp = [[NSMutableArray alloc] init];	
	for (NSDictionary *carnival in bacchanal.carnivalsData)
	{
		NSString *ISOCode = nil;
		NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier: @"en_US"] autorelease];
		NSArray *countryArray = [NSLocale ISOCountryCodes];
		for (NSString *countryCode in countryArray) 
		{
			NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
			if ([[locale displayNameForKey:NSLocaleCountryCode value:countryCode] isEqualToString: [carnival objectForKey:@"country"]]){
				ISOCode = countryCode;
			}
			[pool release];
			
		}
		[temp addObject:[NSDictionary dictionaryWithObjectsAndKeys: [carnival objectForKey:@"city"], @"city", ISOCode, @"ISOCode", nil]];
	}
	temp = [[[NSSet setWithArray:temp] allObjects] retain] ;
	NSSortDescriptor *citySort = [[[NSSortDescriptor alloc] initWithKey:@"city" ascending:YES selector:@selector(compare:)] autorelease	];
	NSArray *descriptors = [NSArray arrayWithObjects:citySort, nil];
	carnivalsTableData = [[temp sortedArrayUsingDescriptors:descriptors ] retain];
	[temp release];
}

-(IBAction)switchViews:(UIBarButtonItem *)sender{
	if (sender.title == @"Cities"){
		self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Years" style:UIBarButtonItemStylePlain target:self action:@selector(switchViews:)] autorelease];
		[iBacchanal sharedUser].selectedView = @"Cities";
		
		[self getCitiesData];
		[carnivalsTableDataView reloadData];
	}
	else{
		self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Cities" style:UIBarButtonItemStylePlain target:self action:@selector(switchViews:)] autorelease];
		
		[iBacchanal sharedUser].selectedView = @"Years";
		
		[self getYearsData];
		[carnivalsTableDataView reloadData];
	}	
}

-(IBAction)addCarnival:(UIBarButtonItem *)sender{
	
	if ([iBacchanal sharedUser].loggedIn){
		[TestFlight passCheckpoint:@"Add A Carnival - Logged in"];
		AddACarnivalViewController *addACarnivalView = [[AddACarnivalViewController alloc] initWithNibName:@"AddACarnival" bundle:nil]; 
		UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:addACarnivalView];
		[addACarnivalView release];
		
		navController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
		[self presentModalViewController:navController animated:YES];
		[navController release];
	}
	else{
		[TestFlight passCheckpoint:@"Add A Carnival - Not logged in"];
		UIAlertView *msg = [[UIAlertView alloc] initWithTitle:nil message:@"You must be logged in to submit events. Goto the \"Account\" Tab to login in or create a new account" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[msg show];
		[msg release];
	}
	
}


-(void)buildTable{
	
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	if (bacchanal.carnivalsData == nil || bacchanal.dataChanged){	
		
		[[StackMob stackmob] get:@"carnivals" withCallback:^(BOOL success, id result) {
			if (success) {
				bacchanal.carnivalsData = [[NSArray alloc] initWithArray:result];
				if([bacchanal.selectedView isEqualToString: @"Years"])
					[self getYearsData];
				else{
					
					[self getCitiesData];}
				[carnivalsTableDataView reloadData];
				
				// object found, cast result to NSArray* and continue with processing
			} else {
				// unable to retrieve object, cast result to NSError* and inspect code & message
				NSLog(@"Error:");
			}
		}];
		
	}
}


// Helper function to size views
- (void)fixupAdView:(UIInterfaceOrientation)toInterfaceOrientation {
 	iBacchanal *bacchanal = [iBacchanal sharedUser];
	if (bacchanal.adBannerView  != nil) {        
        if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) {
            [bacchanal.adBannerView  setCurrentContentSizeIdentifier:
			 ADBannerContentSizeIdentifierLandscape];
        } else {
            [bacchanal.adBannerView  setCurrentContentSizeIdentifier:
			 ADBannerContentSizeIdentifierPortrait];
        }          
        [UIView beginAnimations:@"fixupViews" context:nil];
        if (bacchanal.adBannerViewIsVisible) {
            CGRect adBannerViewFrame = [bacchanal.adBannerView  frame];
            adBannerViewFrame.origin.x = 0;
            adBannerViewFrame.origin.y = 0;
            [bacchanal.adBannerView  setFrame:adBannerViewFrame];
            CGRect contentViewFrame = contentView.frame;
            contentViewFrame.origin.y = [bacchanal getBannerHeight:toInterfaceOrientation];
            contentViewFrame.size.height = self.view.frame.size.height - [bacchanal getBannerHeight:toInterfaceOrientation];
            contentView.frame = contentViewFrame;
        } else {
			[self hideBanner:toInterfaceOrientation];
        }
        [UIView commitAnimations];
    }   
}

-(void)hideBanner:(UIInterfaceOrientation)toInterfaceOrientation{
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	CGRect adBannerViewFrame = [bacchanal.adBannerView frame];
	adBannerViewFrame.origin.x = 0;
	adBannerViewFrame.origin.y = - [bacchanal getBannerHeight:toInterfaceOrientation];
	[bacchanal.adBannerView  setFrame:adBannerViewFrame];
	CGRect contentViewFrame = contentView.frame;
	contentViewFrame.origin.y = 0;
	contentViewFrame.size.height = self.view.frame.size.height + [bacchanal getBannerHeight:toInterfaceOrientation];
	contentView.frame = contentViewFrame;            
 	
}

// Implement AdBannerViewDelegate
#pragma mark ADBannerViewDelegate

- (void)bannerViewDidLoadAd:(ADBannerView *)banner {
   	iBacchanal *bacchanal = [iBacchanal sharedUser];
	if (!bacchanal.adBannerViewIsVisible) {                
        bacchanal.adBannerViewIsVisible = YES;
        [self fixupAdView:[UIDevice currentDevice].orientation];
    }
}

- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error{
   	iBacchanal *bacchanal = [iBacchanal sharedUser];
	if (bacchanal.adBannerViewIsVisible)
    {        
        bacchanal.adBannerViewIsVisible = NO;
        [self fixupAdView:[UIDevice currentDevice].orientation];
    }
}

#pragma mark -
#pragma mark Initialization

/*
 - (id)initWithStyle:(UITableViewStyle)style {
 // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
 self = [super initWithStyle:style];
 if (self) {
 // Custom initialization.
 }
 return self;
 }
 */

#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];
	self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Cities" style:UIBarButtonItemStylePlain target:self action:@selector(switchViews:)] autorelease];
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]  initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addCarnival:)] autorelease];
	
	NSLog(@"Carnival Table");
	
	self.navigationItem.title = @"Carnival Diary";
	
	//contentView.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"iBacchanalBkgd" ]  ];
	
	carnivalsTableDataView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"iBacchanalbkgd.png"]];
	iBacchanal *bacchanal = [iBacchanal sharedUser];
		
	if (bacchanal.selectedView == nil)
		bacchanal.selectedView = @"Years";
	
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;

	//[self createAdBannerView];	
}


/*
 - (void)viewDidAppear:(BOOL)animated {
 [super viewDidAppear:animated];
 
 
 
 }
 */

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	if (bacchanal.networkUp){
		[self buildTable];
		self.navigationItem.rightBarButtonItem.enabled = YES;
		self.navigationItem.leftBarButtonItem.enabled = YES;
	}
	else{
		self.navigationItem.rightBarButtonItem.enabled = NO;
		self.navigationItem.leftBarButtonItem.enabled = NO;
	}
	
	[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];	
	
	[bacchanal.adBannerView setDelegate:self];
	
	[self.view addSubview:bacchanal.adBannerView];
	
	[self fixupAdView:[UIDevice currentDevice].orientation];
}

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    //[self fixupAdView:toInterfaceOrientation];
}


 - (void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
	 
	 [self hideBanner:[UIDevice currentDevice].orientation];
	 [[iBacchanal sharedUser].adBannerView removeFromSuperview];

 }

-(void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
	[[NSNotificationCenter defaultCenter] removeObserver:self];
}



// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return YES; // (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	// Return the number of sections.
	return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	// Return the number of rows in the section.
	return [self.carnivalsTableData count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	static NSString *CellIdentifier = @"Cell";
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
	}
	
	// Configure the cell...
	
	if ([self.navigationItem.leftBarButtonItem.title isEqualToString: @"Cities"]){
		[[cell textLabel] setText:[carnivalsTableData objectAtIndex:indexPath.row]];
		[[cell imageView] setImage:nil];
	}
	else{
		[[cell textLabel] setText:[[carnivalsTableData objectAtIndex:indexPath.row] objectForKey:@"city"]];
		NSString *countryFlag = [NSString stringWithFormat:@"%@.png", [[carnivalsTableData objectAtIndex:indexPath.row] objectForKey:@"ISOCode"]  ];
		[[cell imageView] setImage:[UIImage imageNamed:countryFlag]];
		
	}
	return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
	NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithRange:NSMakeRange('0',10)] invertedSet];
	NSString *trimmed = [[cell textLabel].text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
	BOOL isNumeric = trimmed.length > 0 && [trimmed rangeOfCharacterFromSet:nonNumberSet].location == NSNotFound;
	NSString *temp = [NSString stringWithFormat:@"%@ (Done)",[cell textLabel].text ];
	
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	
	if ((isNumeric) && [[cell textLabel].text intValue] < 2012){
		[[cell textLabel] setTextColor:[UIColor redColor]];
		[[cell textLabel] setText:temp];	
	}
	else{
		[[cell textLabel] setTextColor:[UIColor blackColor]];
		
	}
	
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */


/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source.
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
 }   
 }
 */


/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	// Navigation logic may go here. Create and push another view controller.
	/*
	 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
	 // ...
	 // Pass the selected object to the new view controller.
	 [self.navigationController pushViewController:detailViewController animated:YES];
	 [detailViewController release];
	 */
	
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	
	CarnivalsCategoriesTableDataViewController *carnivalsCategoriesTableDataView = [[CarnivalsCategoriesTableDataViewController alloc] initWithNibName:@"CarnivalsCategoriesTable" bundle:nil];
	self.carnivalsCategoriesTableDataViewController = carnivalsCategoriesTableDataView;
	
	if ([self.navigationItem.leftBarButtonItem.title isEqualToString:@"Cities"]){
		bacchanal.selectedView = @"Years";
		NSLog(@"%@", [carnivalsTableData objectAtIndex:indexPath.row]);
		bacchanal.selectedYear = [carnivalsTableData objectAtIndex:indexPath.row];
		bacchanal.selectedCity = nil;
		
	}
	else{
		bacchanal.selectedView = @"Cities";
		bacchanal.selectedCity = [[carnivalsTableData objectAtIndex:indexPath.row] objectForKey:@"city"];
		bacchanal.selectedYear = nil;
		
	}
	
	//[carnivalsTableData objectAtIndex:indexPath.row];
	
	[self.navigationController pushViewController:carnivalsCategoriesTableDataView animated:YES];
	[carnivalsCategoriesTableDataView release];
	
	//Reuse NavController
	PartyAnimalAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
	[delegate.partyAnimalNavigatorViewController pushViewController:carnivalsCategoriesTableDataViewController animated:YES];
	
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
	[super didReceiveMemoryWarning];
	
	// Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[contentView release];
	[passedValue release];
	[carnivalsTableData release];
	[carnivalsTableDataView release];
	[super dealloc];
}


@end

